package com.hqyj.springBoot.modules.common.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

//这个类的作用是让根本不会进入控制层的错误在页面上显示出来
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class MyBasicErrorController implements ErrorController {
    @Override
    public String getErrorPath() {
        return null;
    }

    @RequestMapping(produces = {"text/html"})
    public ModelAndView errorHtml(HttpServletRequest request) {
        HttpStatus status = this.getStatus(request);
        if(status.value() == 404){
            return new ModelAndView("forward:/common/404");
        }else{
            return new ModelAndView("forward:/common/500");
        }
    }

    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = this.getStatus(request);
        Map<String, Object> map = new HashMap<>();
        if(status.value() == 404){
            map.put("status",404);
            map.put("message","页面走丢了！");
            map.put("data","/common/404");
        }else{
            map.put("status",500);
            map.put("message","服务器出错了！");
            map.put("data","/common/500");
        }

        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity(status);
        }
        return new ResponseEntity(map, status);
    }

    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode);
            } catch (Exception var4) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    }
}
